var $ = window.$;

/**
 * 统一的slide控件管理
 * 配合 g_slide 类
 */

var _pool = {};
var _inited = false;
var _id = 0;
var _count = 0;

var ret = {
	init: function () {
		if(_inited){
			return;
		}
		this.isDrag = false;

		var self = this;
		$(window.document.body).on('mousedown', function(e){
			if(!_count){
				return;
			}
			var target = $(e.target);
			if(!target.hasClass('g_slide_ball')){
				return;
			}
			var conf = _pool[+target.parent().attr("data-id")];
			if(!conf){
				return;
			}
			self.isDrag = true;
			self.current = conf;
			var rect = conf.parent[0].getBoundingClientRect();
			self.leftX = rect.left;
			self.width = rect.right - rect.left;
			rect = e.target.getBoundingClientRect();
			self.width -= (rect.right - rect.left); //减掉ball的宽度
		}).on('mousemove', function (e) {
			if(!self.isDrag){
				return;
			}
			var x = e.pageX - self.leftX;
			if(x > self.width){
				x = self.width;
			}else if(x < 0){
				x = 0;
			}
			var curr = self.current;
			curr.parent.find('.g_slide_ball').css('left', x+"px");
			if(curr.onchange){
				curr.onchange(curr.min + (x / self.width) * (curr.max - curr.min));
			}
		}).on('mouseup', function (e) {
			if(!self.isDrag){
				return;
			}

			self.isDrag = false;
			self.current = null;
		});
	},

	on: function(conf){
		this.init();
		if(!conf.parent){
			return;
		}
		conf.min = conf.min || 0;
		conf.max = conf.max || 1;
		conf.parent.attr("data-id",++_id);

		_pool[_id] = conf;
		_count++;
		return _id;
	},

	off: function(id){
		if(_pool[id]){
			delete _pool[id];
			_count--;
		}
	},

	setVal: function(id, val, trigger){
		var conf = _pool[id];
		if(!conf){
			return;
		}
		val = val || 0;
		if(val < conf.min){
			val = conf.min;
		}else if(val > conf.max){
			val = conf.max;
		}
		var width = conf.parent.width();
		width -= conf.parent.find('.g_slide_ball').width(); //减掉ball的宽度
		var x = width * ((val - conf.min) / (conf.max - conf.min));
		if(typeof x != 'number'){
			x = 0;
		}
		conf.parent.find('.g_slide_ball').css("left", x+"px");
		if(trigger && conf.onchange){
			conf.onchange(val);
		}
	}
};

module.exports = ret;